import config from "./config.js";
import axios from "axios";
// import qs from "qs";

import router from "@/router";
import util from "@/utils/util";
import { ElMessage } from "element-plus";

//	post请求
export const request = function (params) {
  return new Promise((resolve, reject) => {
    // 接口访问类型 处理成小写
    const method = (params.method || "post").toLowerCase();
    // application/json 请求数组配置
    let headers = params.headers || {
      // "Content-Type": ["get"].includes(method)
      //   ? "application/x-www-form-urlencoded;charset=UTF-8"
      //   : "application/json;charset=UTF-8",
      "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
    };
    const token = localStorage.getItem("token") || "";
    headers.token = `${token}`;
    // headers.Authorization = `Bearer ${token}`;

    // 请求地址
    var url = `${config.host}${params.url || ""}`;

    // 接口參數
    let axiosData = {
      data: params.data || {},
      params: params.data || {},
    };
    if (["post", "put"].includes(method)) delete axiosData.params;
    else delete axiosData.data;

    let axios_data = {
      headers,
      url,
      method,
      timeout: 99999,
      ...axiosData,
      dataType: "json",
    };

    if (params["responseType"]) {
      axios_data["responseType"] = params["responseType"];
    }

    axios(axios_data)
      .then((res) => {
        // 获取文件
        if (config.get_file_api == params.url) return resolve(res.data);

        // 下载
        if (params.responseType && params.responseType == "blob") {
          resolve(res);
          return;
        }

        // 请求异常
        if (res.data.e != 0) {
          // 弹窗提示
          if (params.alert == true) {
            ElMessage.warning(res.data.msg);
          }

          // resolve('');
          return "";
        }

        resolve(res.data || {});
      })
      .catch((err) => {
        if (err.response.status == 401) {
          // 若未登录则自动跳转login;
          router.push(`/login`);
          return;
        }

        const data = err.response?.data || {};
        ElMessage.warning(data.m);

        reject(data);
      });
  });
};

// post请求
export const upload = function (params) {
  return new Promise((resolve, reject) => {
    //	请求地址
    var url = config.host + (params.url || config.upload_file_api);

    let headers = params.header || {
      "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
    };
    const token = localStorage.getItem("token") || "";
    headers.Authorization = `Bearer ${token}`;

    //	初始化表单数据
    var forms = new FormData();
    //	将文件塞入表单里去
    forms.append("file", params.file);

    // 发起网络请求
    axios({
      headers,
      url,
      method: params.method || "POST",
      data: forms,
    })
      .then((res) => {
        if (res.data.code != 200) {
          ElMessage.warning(res.data.msg);
          return "";
        }
        resolve(res.data);
      })
      .catch((err) => {
        reject(err);
      });
  });
};

// 请求
async function requestGo(method = "get", url, data) {
  const res = await request({
    method,
    url,
    data,
    alert: true,
  });
  // console.log("requestGo", res);
  return res.d || {};
}

// 请求
export const apiGo = {
  get(url = "", data = {}) {
    return requestGo("get", url, data);
  },
  post(url = "", data = {}) {
    return requestGo("post", url, data);
  },
};
